/**
 * Copyright (C), 2001-2031, www.bosssof.com.cn
 * FileName: UserController.java
 * Author: WangXin
 * Date: 2024/6/1 下午6:25
 * Description:
 * <p>
 * History:
 * Date          Author   Version  Desc
 * 2024-01-01    bosssoft  1.0.0   initialize this file
 */
package com.bosssoft.g1.controller;

/**
 * @className: UserController
 * @description:
 * 解决什么问题：
 *  演示线程池的正确使用 
 * 主要方法和数据成员：
 *  methodxx 使用 ThreadPoolExecutor创建线程进行任务操作
 * 注意事项：
 *  例如：该类需要从容器获取不可以new   
 * @author: WangXin
 * @date: 2024/6/1下午6:25
 * @since 1.0
 **/

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.bosssoft.g1.common.annotation.ApiLog;
import com.bosssoft.g1.common.data.dto.IdVersion;
import com.bosssoft.g1.common.data.vo.CommonResponse;
import com.bosssoft.g1.common.exception.parse.BusinessException;
import com.bosssoft.g1.api.UserApi;
import com.bosssoft.g1.dto.DepartmentDTO;
import com.bosssoft.g1.dto.PageDTO;
import com.bosssoft.g1.dto.UserDTO;
import com.bosssoft.g1.dto.UserRoleRequestDTO;
import com.bosssoft.g1.entity.Role;
import com.bosssoft.g1.entity.User;
import com.bosssoft.g1.query.UserQuery;
import com.bosssoft.g1.service.RoleService;
import com.bosssoft.g1.service.UserService;
import com.bosssoft.g1.utils.CommonResponseUtils;
import com.bosssoft.g1.vo.IdNameVO;
import com.bosssoft.g1.vo.RoleVO;
import com.bosssoft.g1.vo.UserVO;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName UserController
 * @Description  用户管理接口
 * @Author yangshaoqi
 * @Date 2020/12/14 21:11
 * @Version 1.0
 **/
@RestController
public class UserController implements UserApi{

    private final UserService userService;
    // 构造器注入UserService
    @Autowired
    public UserController(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    RoleService roleService;

    /**
     * 获取所有用户信息
     */
    @Override
    public CommonResponse<PageInfo<UserVO>> getAllUsers(PageDTO pageDTO) {
        PageInfo<UserDTO> userDTOPageInfo = userService.getAllUsers(pageDTO);

        if (userDTOPageInfo != null) {
            List<UserVO> userVOList = userDTOPageInfo.getList().stream()
                    .map(this::convertToUserVO)
                    .collect(Collectors.toList());

            PageInfo<UserVO> userVOPageInfo = new PageInfo<>(userVOList);
            userVOPageInfo.setPageNum(userDTOPageInfo.getPageNum());
            userVOPageInfo.setPageSize(userDTOPageInfo.getPageSize());
            userVOPageInfo.setTotal(userDTOPageInfo.getTotal());
            userVOPageInfo.setPages(userDTOPageInfo.getPages());
            userVOPageInfo.setSize(userDTOPageInfo.getSize());

            return CommonResponseUtils.success(userVOPageInfo);
        } else {
            return CommonResponseUtils.failed("查询用户信息失败");
        }
    }

    /**
     * 将userDTO转化为userVO
     * @param userDTO
     * @return
     */
    private UserVO convertToUserVO(UserDTO userDTO) {
        UserVO userVO = new UserVO();
        userVO.setId(userDTO.getId());
        userVO.setCode(userDTO.getCode());
        userVO.setName(userDTO.getName());
        userVO.setCompanyName(userDTO.getCompanyName());
        userVO.setCompanyName(userDTO.getCompanyName());
        userVO.setDepartmentName(userDTO.getDepartmentName());
        userVO.setRoleName(userDTO.getRoleName());
        userVO.setPositionName(userDTO.getPositionName());
        userVO.setSex(userDTO.getSex());
        userVO.setBirthday(userDTO.getBirthday());
        userVO.setTel(userDTO.getTel());
        userVO.setStatus(userDTO.getStatus());
        userVO.setEmail(userDTO.getEmail());
        userVO.setCreatedTime(userDTO.getCreatedTime());
        userVO.setUpdatedTime(userDTO.getUpdatedTime());

        return userVO;
    }


    @Override
    public CommonResponse<List<IdNameVO>> getAllDepartment() {
        List<IdNameVO> departments=userService.getAllDepartments();
        if(departments != null){
            return CommonResponseUtils.success(departments);
        }else{
            return CommonResponseUtils.failed("查询用户信息失败");
        }
    }

    @Override
    public CommonResponse<List<IdNameVO>> getAllRole() {
        List<IdNameVO> roles=userService.getAllRoles();
        if(roles != null){
            return CommonResponseUtils.success(roles);
        }else{
            return CommonResponseUtils.failed("查询用户信息失败");
        }
    }

    @Override
    public CommonResponse<List<IdNameVO>> getAllPosition() {
        List<IdNameVO> positions=userService.getAllPositions();
        if(positions != null){
            return CommonResponseUtils.success(positions);
        }else{
            return CommonResponseUtils.failed("查询用户信息失败");
        }
    }

    /**
     * 按钮查询
     */
    @Override
    public CommonResponse<PageInfo<UserVO>> queryUser( @RequestBody UserQuery userQuery) {
        PageInfo<UserDTO> userDTOPageInfo =userService.searchUser(userQuery);

        if (userDTOPageInfo != null) {
            List<UserVO> userVOList = userDTOPageInfo.getList().stream()
                    .map(this::convertToUserVO)
                    .collect(Collectors.toList());

            PageInfo<UserVO> userVOPageInfo = new PageInfo<>(userVOList);
            userVOPageInfo.setPageNum(userDTOPageInfo.getPageNum());
            userVOPageInfo.setPageSize(userDTOPageInfo.getPageSize());
            userVOPageInfo.setTotal(userDTOPageInfo.getTotal());
            userVOPageInfo.setPages(userDTOPageInfo.getPages());
            userVOPageInfo.setSize(userDTOPageInfo.getSize());

            return CommonResponseUtils.success(userVOPageInfo);
        } else {
            return CommonResponseUtils.failed("查询用户信息失败");
        }
    }

    /**
     * 查询角色信息
     */
    @Override
    public CommonResponse<UserVO> queryUserById(Long id) {
        UserDTO userDTO=userService.queryUserById(id);
        UserVO userVO = convertToUserVO(userDTO);

        return CommonResponseUtils.success(userVO);
    }

    /**
     * 新增用户信息
     * @param userDTO 用户信息
     * @return
     */
    @Override
    public CommonResponse<Boolean> add(@NotNull @Valid @RequestBody @ApiParam(value = "用户数据", required = true) UserDTO userDTO) {
        return CommonResponseUtils.booleanResult(userService.add(userDTO));
    }

    /**
     * 删除单个用户
     */
    @Override
    public CommonResponse<Boolean> remove(@NotNull @RequestParam Long id) {
        return CommonResponseUtils.booleanResult(userService.remove(id));
    }

    @Override
    public CommonResponse<Boolean> batchRemove(@NotEmpty @RequestBody List<UserDTO> userDTO) {
        return CommonResponseUtils.booleanResult(userService.batchRemove(userDTO));
    }
    /**
     * 通过用户id修改用户信息
     * 弹出框显示信息时调用 查询单个用户信息 queryUserById
     * @param userDTO
     * @return CommonResponse
     */
    @Override
    public CommonResponse<Boolean> updateUser(@NotNull @RequestBody UserDTO userDTO) {
        try {
            Boolean result = userService.updateUser(userDTO);
            if (result) {
                return CommonResponseUtils.success(result);
            } else {
                return CommonResponseUtils.failed("修改失败");
            }
        } catch (BusinessException e) {
            return CommonResponseUtils.failedWithMsg("修改失败：",e.getMessage());
        }
    }

    /**
     * 用户分配
     *
     * @param userRoleRequest
     * @return CommonResponse
     */
    @Override
    public CommonResponse<Boolean> userAssign(@RequestBody UserRoleRequestDTO userRoleRequest) {
        // 獲取請求參數
        List<Long> userIds = userRoleRequest.getUserIds();
        List<Long> roleIds = userRoleRequest.getRoleIds();

        if (ObjectUtil.isNull(userRoleRequest) || CollectionUtil.isEmpty(userIds) || CollectionUtil.isEmpty(roleIds)) {
            return CommonResponseUtils.failed("參數傳遞錯誤");
        }

        boolean flag = userService.userAssign(userIds, roleIds);
        if (flag) {
            return CommonResponseUtils.success("插入成功");
        } else {
            return CommonResponseUtils.failed("没有完全插入");
        }
    }

    /**
     * 获取公司角色列表
     *
     * @param userId
     * @return CommonResponse
     */
    @Override
    public CommonResponse<PageInfo<Role>> getCompanyRoleList(@RequestParam("userId") Long userId, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize) {
        // 获取用户
        User user = userService.getUserById(userId);
        Long companyId = user.getCompanyId();
        PageInfo<Role> companyRoleList=roleService.getCompanyRoleList(companyId,pageNum,pageSize);
        if(companyRoleList != null){
            return CommonResponseUtils.success(companyRoleList);
        }else{
            return CommonResponseUtils.failed("获取公司角色列表失败");
        }

        /*// 获取用户
        User user = userService.getUserById(userId);

        if (ObjectUtil.isNull(user)) {
            return CommonResponseUtils.failed("用户不存在");
        }

        // 获取公司对应的所有角色的
        return CommonResponseUtils.success(roleService.getCompanyRoleList(user.getCompanyId(), pageNum, pageSize));*/
    }

    /**
     * 启功能
     *
     * @param ids
     * @return CommonResponse
     */
    @Override
    public CommonResponse<Boolean> start(List<Long> ids) {
        userService.changeStatus(ids, 1);
        return CommonResponseUtils.success();
    }

    /**
     * 停功能
     *
     * @param ids
     * @return CommonResponse
     */
    @Override
    public CommonResponse<Boolean> stop(List<Long> ids) {
        userService.changeStatus(ids, 2);
        return CommonResponseUtils.success();
    }

    @Override
    public CommonResponse<Map<String,List>> getUserRolePositionDepartmentTree(@NotNull Long id){
        return CommonResponseUtils.success(userService.getUserRolePositionDepartmentTree(id));
    }

    /**
     * 根据部门id查询用户主页
     * @param pageNum
     * @param pageSize
     * @param id
     * @return
     */
    @Override
    public CommonResponse<PageInfo<UserVO>> getUserByDepartment(@NotNull @Valid int pageNum,int pageSize,Long id){
        PageInfo<UserDTO> userDTOPageInfo = userService.getUsersByDepartmentId(pageNum,pageSize,id);

        if (userDTOPageInfo != null) {
            List<UserVO> userVOList = userDTOPageInfo.getList().stream()
                    .map(this::convertToUserVO)
                    .collect(Collectors.toList());

            PageInfo<UserVO> userVOPageInfo = new PageInfo<>(userVOList);
            userVOPageInfo.setPageNum(userDTOPageInfo.getPageNum());
            userVOPageInfo.setPageSize(userDTOPageInfo.getPageSize());
            userVOPageInfo.setTotal(userDTOPageInfo.getTotal());
            userVOPageInfo.setPages(userDTOPageInfo.getPages());
            userVOPageInfo.setSize(userDTOPageInfo.getSize());

            return CommonResponseUtils.success(userVOPageInfo);
        } else {
            return CommonResponseUtils.failed("查询用户信息失败");
        }
    }

    /**
     * 根据职位id获取用户主页信息
     * @param pageNum
     * @param pageSize
     * @param id
     * @return
     */
    @Override
    public CommonResponse<PageInfo<UserVO>> getUserByPosition(@NotNull @Valid int pageNum,int pageSize,Long id){
        PageInfo<UserDTO> userDTOPageInfo = userService.getUsersByPositionId(pageNum,pageSize,id);

        if (userDTOPageInfo != null) {
            List<UserVO> userVOList = userDTOPageInfo.getList().stream()
                    .map(this::convertToUserVO)
                    .collect(Collectors.toList());

            PageInfo<UserVO> userVOPageInfo = new PageInfo<>(userVOList);
            userVOPageInfo.setPageNum(userDTOPageInfo.getPageNum());
            userVOPageInfo.setPageSize(userDTOPageInfo.getPageSize());
            userVOPageInfo.setTotal(userDTOPageInfo.getTotal());
            userVOPageInfo.setPages(userDTOPageInfo.getPages());
            userVOPageInfo.setSize(userDTOPageInfo.getSize());

            return CommonResponseUtils.success(userVOPageInfo);
        } else {
            return CommonResponseUtils.failed("查询用户信息失败");
        }
    }

    @Override
    public CommonResponse<PageInfo<UserVO>> getUserByRole(@NotNull @Valid int pageNum,int pageSize,Long id){
        PageInfo<UserDTO> userDTOPageInfo = userService.getUsersByRoleId(pageNum,pageSize,id);

        if (userDTOPageInfo != null) {
            List<UserVO> userVOList = userDTOPageInfo.getList().stream()
                    .map(this::convertToUserVO)
                    .collect(Collectors.toList());

            PageInfo<UserVO> userVOPageInfo = new PageInfo<>(userVOList);
            userVOPageInfo.setPageNum(userDTOPageInfo.getPageNum());
            userVOPageInfo.setPageSize(userDTOPageInfo.getPageSize());
            userVOPageInfo.setTotal(userDTOPageInfo.getTotal());
            userVOPageInfo.setPages(userDTOPageInfo.getPages());
            userVOPageInfo.setSize(userDTOPageInfo.getSize());

            return CommonResponseUtils.success(userVOPageInfo);
        } else {
            return CommonResponseUtils.failed("查询用户信息失败");
        }
    }
}
